<template>
  <view class="live">
    <u-sticky>
      <view class="sticky">
        <view class="play-box">
          <video class="player" id="player" :autoplay="true" :src="url" :initial-time="initialtime"
            :title="current.name" enable-play-gesture :play-strategy="2" :poster="current.face"
            @timeupdate="videoTimeUpdateEvent"></video>
        </view>
        <u-cell-item :arrow="false">
          <view slot="title">
            <text selectable>节目列表</text>
          </view>
          <text>来源：</text>
          <text>{{ site.name }}</text>
        </u-cell-item>
      </view>
    </u-sticky>
    <view class="paly-list">
      <view class="channel">
        <scroll-view scroll-y="true" style="height: 100%;">
          <view v-for="(item,index) in channelList" :key="index">
            <view :style="{backgroundColor:item== curChannel?'#EEE':'' }">
              <u-cell-item :arrow="false" @click="handleChannelClick(item)">
                <view slot="title">{{ item.name }}</view>
              </u-cell-item>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="channel-list">
        <scroll-view scroll-y="true" style="height: 100%;">
          <view class="play-loading" v-if="loading">
            <text>数据加载中...</text>
          </view>
          <view class="list-box" v-else>
            <view v-for="(item,index) in playList" :key="index" class="channel-item"
              @click="handleItemClick(item,index)">
              <u-image :src="item.face" lazy-load border-radius="5px" width="150upx" height="150upx" mode="widthFix">
                <view slot="error" style="font-size: 24rpx;width: 150upx; height: 150upx;">加载失败</view>
              </u-image>
              <view class="u-text-center">
                <text class="u-line-2">{{ item.name }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
  import http from "@/utils/request.js"
  import Tools from "@/utils/tools.js"
  export default {
    data() {
      return {
        current: {
          name: ''
        },
        curChannel: null,
        initialtime: 0,
        site: {
          name: '未知'
        },
        url: '',
        loading: false,
        channelList: [],
        playList: [],
        videoUpdateCounter: 0,
        videoCtx: null,
      }
    },
    onHide() {
      if (this.videoCtx) {
        this.videoCtx.stop()
      }

      // console.log('onHide')
    },
    mounted() {
      this.videoCtx = uni.createVideoContext('player', this)
      // console.log(this.videoCtx)
    },
    created() {
      this.fetchData()
      this.site.name = this.defcku.name
    },
    methods: {
      fetchData() {
        let list = this.defcku.iptv
        this.channelList = list
        if (list.length > 0) {
          this.handleChannelClick(list[0])
        }
      },
      async videoTimeUpdateEvent(e) {
        // 播放进度变化时触发timeupdate，event.detail = {currentTime, duration} 。触发频率 250ms 一次
        this.videoUpdateCounter += 1
        if (this.videoUpdateCounter % 40 === 0) {
          // 每10秒更新一下历史记录的时间进度
          this.videoUpdateCounter = 0
          // await this.updateHistory(e.detail)
        }
      },
      async updateHistory(detail) {
        const res = await db.get('history', `${this.siteKey}-${this.id}`)
        if (res.flag) {
          res.data.currentTime = detail.currentTime
          res.data.duration = detail.duration
          await db.update('history', res.data)
        }
      },
      fetchH5PlayList() {
        this.playList = [{
            "id": "#EXTINF:-1,tvg-id=\"CCTV2\"",
            "name": "CCTV2",
            "face": "https://epg.112114.xyz/logo/CCTV2.png",
            "url": "https://live.v1.mk/api/bestv.php?id=cctv2hd8m/8000000"
          },
          {
            "id": "#EXTINF:-1,tvg-id=\"CCTV3\"",
            "name": "CCT456456465V3",
            "face": "https://epg.112114.xyz/logo/欢笑剧场.png",
            "url": "https://live.v1.mk/api/bestv.php?id=cctv38m/8000000"
          },
          {
            "id": "#EXTINF:-1,tvg-id=\"CCTV3\"",
            "name": "CCTV4",
            "face": "https://epg.112114.xyz/logo/CCTV3.png",
            "url": "https://live.v1.mk/api/bestv.php?id=cctv38m/8000000"
          },
          {
            "id": "#EXTINF:-1,tvg-id=\"CCTV3\"",
            "name": "CCTV5",
            "face": "https://epg.112114.xyz/logo/CCTV3.png",
            "url": "https://live.v1.mk/api/bestv.php?id=cctv38m/8000000"
          }
        ]
      },
      handleChannelClick(item) {
        this.curChannel = item
        // console.log(item)
        // #ifdef H5

        // this.loading = true
        // setTimeout(() => {
        //   this.fetchH5PlayList()
        //   this.loading = false
        // }, 2000)

        // return
        // #endif

        this.loading = true
        this.$u.get(item.url).then(response => {
            let list = Tools.parseIPTV(response)
            this.playList = list
            // console.log(list)
            if (list.length == 0) {
              console.log(response)
            }
          }).catch(err => {
            console.log(err)
            if (err.errMsg) {
              err = err.errMsg
            }
            this.$u.toast('数据加载失败' + err)
          })
          .finally(() => {
            this.loading = false
          })
      },
      handleItemClick(obj, index) {
        this.current = obj
        this.url = obj.url
        uni.setNavigationBarTitle({ title: `直播 (${ obj.name })` })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .live {
    .play-box {
      .player {
        width: 100vw;
        height: 35vh;
      }
    }

    .sticky {
      background-color: #FFF;
      box-sizing: border-box;
      border: 0px solid #096;
      height: 45vh;
    }

    .paly-list {
      /* #ifdef H5 */
      height: calc(100vh - 60vh);
      /* #endif */
      /* #ifdef APP-PLUS */
      height: calc(100vh - 46vh);
      /* #endif */
      border: 0px solid #0000ff;
      box-sizing: border-box;
      border-radius: 10upx;
      display: flex;

      .channel {
        width: 200upx;
        height: 100%;
        border: 0px solid #096;
        // background-color: rgba(240, 240, 240, 0.5);
      }

      .channel-list {
        --n: 3;
        --w: 170upx;
        width: 100%;
        margin-left: 0px;
        border: 1px solid #EEE;

        // background-color: #252c58;
        .play-loading {
          font-size: 12px;
          height: 400upx;
          line-height: 400upx;
          text-align: center;
          color: #808080;
        }

        .list-box {
          padding: 5px;
          display: flex;
          flex-wrap: wrap;
          border-radius: 5px;

          .u-image {
            border: 0px solid #252c58;
            margin: 0px auto;
          }

          .channel-item {
            width: var(--w);
            background-color: #EEE;
            border-radius: 5px;
            border: 1px solid #EEE;
            box-sizing: border-box;
            overflow: hidden;
            margin: 5px calc((100% - var(--w) * var(--n)) / var(--n)/ 2);
            padding: 2px;
          }
        }
      }
    }

  }
</style>